<template>
  <div class="pane-account">
    <el-form :model="form" label-width="60px" :rules="rules" ref="formRef" status-icon>
      <el-form-item label="账号" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { reactive, ref } from 'vue'
  import type { IAccount } from '@/services/login/type'
  import useLoginStore from '@/store/login'
  import { localCache } from '@/utils/cache'
  import { CACHE_NAME, CACHE_PASSWORD } from '@/global/constant'

  defineProps({
    loading: {
      type: Boolean,
      defalut: false
    }
  })

  const $emits = defineEmits(['update:loading'])

  const form = reactive<IAccount>({
    // name: 'coderwhy',
    // password: '123456'
    name: localCache.getCache(CACHE_NAME) ?? '',
    password: localCache.getCache(CACHE_PASSWORD) ?? ''
  })
  const formRef = ref<FormInstance>()
  const rules = reactive<FormRules<IAccount>>({
    name: [
      {
        required: true,
        message: '请输入账号',
        trigger: 'blur'
      },
      {
        // {6,20}数字之间不能使用空格
        pattern: /^[a-z0-9]{6,20}$/,
        message: '账号长度在6-20之间',
        trigger: 'change'
      }
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
        trigger: 'blur'
      },
      {
        pattern: /^[a-z0-9]{3,}$/,
        message: '账号长度在3以上',
        trigger: 'change'
      }
    ]
  })

  const loginStore = useLoginStore()
  function loginAction(isRemPwd: boolean) {
    formRef.value?.validate((valid) => {
      if (!valid) return
      // 登陆操作
      $emits('update:loading', true)
      loginStore
        .loginIAccountAction(form)
        .then(() => {
          ElMessage.success('登陆成功')
          if (isRemPwd) {
            localCache.setCache(CACHE_NAME, form.name)
            localCache.setCache(CACHE_PASSWORD, form.password)
          } else {
            localCache.removeCache(CACHE_NAME)
            localCache.removeCache(CACHE_PASSWORD)
          }
        })
        .finally(() => $emits('update:loading', false))
    })
  }

  defineExpose({
    loginAction
  })
</script>

<style lang="scss" scoped></style>
